/**************************************
                       服务器端
					   ***************************************/
					   /*加载库文件*/
#include <winsock2.h>
#include <stdio.h>
#include <windows.h>
#include <time.h>　　
#pragma comment(lib,"WS2_32.lib")

int main(int argc, char*argv[])
{
	/*加载winsock文件*/
	WSADATA wsaData;
	WORD sockVersion = MAKEWORD(2, 0);
	::WSAStartup(sockVersion, &wsaData);

	SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	/*创建服务器端的套接字，三个参数分别代表 使用TCP/IP;传输过程使用TCP;不适用其他特殊协议*/

	if (s == INVALID_SOCKET)
	{
		printf("Failed socket()\n");
		::WSACleanup();
		return 0;
	}

	/*socket中装入地址信息*/
	sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(13);          /*表示服务器监听的端口号为13*/
	sin.sin_addr.S_un.S_addr = INADDR_ANY;

	/*绑定地址及端口号*/
	if (::bind(s, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
	{
		printf("Failed bind()\n");
		::WSACleanup();
		return 0;
	}

	/*监听客户端的连接请求*/
	if (::listen(s, 2) == SOCKET_ERROR)
	{
		printf("Failed listen()\n");
		::WSACleanup();
		return 0;
	}
	sockaddr_in remoteAddr;
	int nAddrLen = sizeof(remoteAddr);
	SOCKET client;

	time_t t = time(0);
	char tmp[64];
	strftime(tmp, sizeof(tmp), "%Y/%m/%d %X %A\n\t", localtime(&t));

	/*循环接受连接请求*/
	while (TRUE)
	{
		client = ::accept(s, (SOCKADDR*)&remoteAddr, &nAddrLen);
		if (client == INVALID_SOCKET)
		{
			printf("Failed accept()\n");
			continue;
		}
		printf("接收到一个客户端的连接：%s\r\n\n等待下一个客户端的连接……\n\n", inet_ntoa(remoteAddr.sin_addr));
		printf("服务器实现者学号：20191326");
		::send(client, tmp, strlen(tmp), 0); /*发送本地时间给客户端*/

		::closesocket(client); /*关闭连接*/
	}

	::closesocket(s);/*关闭套接字*/

	::WSACleanup();
	return 0;

}